package com.demo.syslog.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SyslogClient {

	public static void main(String[] args) throws SocketException, UnknownHostException{
		int recvTimeout=200000000;
		int MAXNUM=3;
		DatagramSocket client=new DatagramSocket();
		client.setSoTimeout(recvTimeout);
		
		InetAddress loc = InetAddress.getLocalHost(); 
		byte[] sendData=new byte[]{};
		DatagramPacket sendPacket=new DatagramPacket(sendData,0,0,loc,3000);
		
		byte[] buf = new byte[1024];
		DatagramPacket receivePacket = new DatagramPacket(buf, 1024);
		
		int tries = 0;                         //重发数据的次数  
        boolean receivedResponse = false;     //是否接收到数据的标志位  
        //直到接收到数据，或者重发次数达到预定值，则退出循环  
        while(!receivedResponse && tries<MAXNUM){  
            try{
            	//发送数据  
            	client.send(sendPacket);  
                //接收从服务端发送回来的数据  
            	client.receive(receivePacket);  
                //如果接收到的数据不是来自目标地址，则抛出异常  
                if(!receivePacket.getAddress().equals(loc)){  
                    throw new IOException("Received packet from an umknown source");  
                }  
                //如果接收到数据。则将receivedResponse标志位改为true，从而退出循环  
                receivedResponse = true;  
            }catch(Exception e){  
                //如果接收数据时阻塞超时，重发并减少一次重发的次数  
                tries += 1;  
                System.out.println("Time out," + (MAXNUM - tries) + " more tries..." );  
            }  
        }  
        if(receivedResponse){  
            //如果收到数据，则打印出来  
            System.out.println("client received data from server：");  
            String str_receive = new String(receivePacket.getData(),0,receivePacket.getLength()) +   
                    " from " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort();  
            System.out.println(str_receive);  
            //由于dp_receive在接收了数据之后，其内部消息长度值会变为实际接收的消息的字节数，  
            //所以这里要将dp_receive的内部消息长度重新置为1024  
            receivePacket.setLength(1024);     
        }else{  
            //如果重发MAXNUM次数据后，仍未获得服务器发送回来的数据，则打印如下信息  
            System.out.println("No response -- give up.");  
        }  
        client.close();  
	}
}
